package main

import (
	"fmt"
	"github.com/json-iterator/go"
	"strings"
)

type Response struct {
	Code int
	Msg  string
	Data interface{}
}

type People struct {
	ID   int
	Name string
}

func main() {
	var people = People{1, "张三"}
	people_Arr := [2]People{people, people}
	var response = Response{
		Code: 200,
		Msg:  "success",
		Data: people_Arr,
	}

	str := objToJson(response)
	fmt.Println("使用iterator将对象转换为字符串:\n", str)
	resp := jsonToObj(str)
	fmt.Printf("使用iterator将字符串转换为对象:\n%+v\n", resp)
	lean1()
	lean2()

}

//json字符串转对象
func jsonToObj(jsonStr string) Response {
	var resp Response
	var jsonByte = []byte(jsonStr)
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	json.Unmarshal(jsonByte, &resp)

	return resp
}

//object转字符串
func objToJson(response Response) string {
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	str, err := json.MarshalToString(response)
	if err != nil {
		fmt.Println("error", err)
	}

	return str
}

//取json字符串中的值
func lean1() {
	val := []byte(`{"ID":1,
		"Name":"Reds",
		"Colors":["Crimson","Red","Ruby","Maroon"],
		"Data":[{"ID":1,"Name":"张三"},{"ID":1,"Name":"张三"}]}`)

	str := jsoniter.Get(val, "Colors", 1).ToString()
	fmt.Println("直接取值:", str)

	var peo People = jsoniter.Get(val, "Data")

	fmt.Printf("直接取值:%+v\n", peo)
}

func lean2() {
	json := jsoniter.ConfigCompatibleWithStandardLibrary
	reader := strings.NewReader(`{
		"ID":1,
		"Name":"Reds",
		"Colors":["Crimson","Red","Ruby","Maroon"]}`)

	decoder := json.NewDecoder(reader)
	params := make(map[string]interface{})
	err := decoder.Decode(&params)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%+v\n", params)
	}

}
